//
//  AppDelegate.m
//  BlockBrowser
//
//  Created by Mac on 2018/3/28.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#import "AppDelegate.h"
#import "TMTabbarViewController.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import "JPUSHService.h"
#import <UserNotifications/UserNotifications.h>
//使用huangjin 开发者账号
@interface AppDelegate ()<WXApiDelegate,TencentApiInterfaceDelegate,JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [BBSystemManger manger];//更新系统配置
    [[TencentOAuth alloc] initWithAppId:TencentQQAppid andDelegate:self];
    // Override point for customization after application launch.
    [SVProgressHUD setMinimumDismissTimeInterval:3];
    self.window = [[UIWindow alloc] initWithFrame:UIScreenFrame];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    self.window.rootViewController = [TMTabbarViewController new];
    if ([STUserManger defult].loginedUser.userID) {
        [TMUtils autoLogin];
    }
    bool success =  [WXApi registerApp:wechatID];
    //配置推送
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self configJpush:launchOptions];
    });
    
    
    return YES;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    if ([url.description containsString:wechatID]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return [TencentOAuth HandleOpenURL:url];
    
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    if ([url.description containsString:wechatID]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    if ([url.scheme isEqualToString:[NSString stringWithFormat:@"tencent%@",TencentQQAppid]]) {
        [QQApiInterface handleOpenURL:url delegate:self.window.rootViewController];
    }
    
    bool login = [TencentOAuth HandleOpenURL:url];
    return login;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    self.registrationID = [JPUSHService registrationID];
    NSString *token =
    [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
                                                           withString:@""]
      stringByReplacingOccurrencesOfString:@">"
      withString:@""]
     stringByReplacingOccurrencesOfString:@" "
     withString:@""];
    self.token = token;
    
}
#pragma mark --微信事件回调
#pragma mark --WXApiDelegate
- (void)onResp:(BaseResp*)resp{
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp * loginresp = (SendAuthResp*)resp;
        NSString * token = loginresp.code;
        NSLog(@"%d",loginresp.errCode);
        NSLog(@"%@",token);
        if (resp.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信登录"];
        }
        if (resp.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝了微信登录"];
        }
        if (resp.errCode == 0) {
             [SVProgressHUD showSuccessWithStatus:@"微信登录成功"];
            NSString * url =   [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",wechatID,wechatSecret,token];
           // [self fetchWeChatOpenIdRequestWithUrl:url];
            // https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        }
    }
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        SendMessageToWXResp * share = (SendMessageToWXResp*)resp;
        NSLog(@"%d",share.errCode);
        if (resp.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信分享"];
        }
        if (resp.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝微信分享"];
        }
        if (resp.errCode == 0) {
            [TMUtils sendGetShareAwardRequest];
            //[SVProgressHUD showSuccessWithStatus:@"微信分享成功"];
        }
    }
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp * pay = (PayResp*)resp;
        NSLog(@"%d",pay.errCode);
        if (pay.errCode == -2) {
            [SVProgressHUD showErrorWithStatus:@"您取消了微信支付"];
        }
        if (pay.errCode == -4) {
            [SVProgressHUD showErrorWithStatus:@"您拒绝微信支付"];
        }
        if (pay.errCode == 0) {
            [SVProgressHUD showSuccessWithStatus:@"微信支付成功"];
        }
    }
}
- (BOOL)onTencentReq:(TencentApiReq *)req{
    return YES;
}

- (BOOL)onTencentResp:(TencentApiResp *)resp{
    return YES;
}
#pragma mark --TencentSessionDelegate
- (void)responseDidReceived:(APIResponse*)response forMessage:(NSString *)message{
    
    
}
- (void)configJpush:(id)launchOptions{
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
     
                      selector:@selector(networkDidReceiveMessage:)
     
                          name:kJPFNetworkDidReceiveMessageNotification
     
                        object:nil];
    
    
#ifdef DEBUG
    [JPUSHService setupWithOption:launchOptions
                           appKey:jpushAppKey
                          channel:@"noren"
                 apsForProduction:0];
#else
    [JPUSHService setupWithOption:launchOptions
                           appKey:jpushAppKey
                          channel:@"noren"
                 apsForProduction:1];
#endif
    
    
    
}
#pragma mark- JPUSHRegisterDelegate

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}
#pragma mark- JPUSHRegisterDelegate
//前台
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger options))completionHandler{
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
    
    
}
//关闭状态
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
    
    completionHandler();
    
}
#pragma mark --notifacation
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    
    NSDictionary *userInfo = [notification userInfo];
    
    NSString *title = [userInfo valueForKey:@"title"];
    
    NSString *content = [userInfo valueForKey:@"content"];
    
    NSDictionary *extra = [userInfo valueForKey:@"extras"];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    
    NSString *currentContent = [NSString
                                
                                stringWithFormat:
                                
                                @"收到自定义消息:%@\ntitle:%@\ncontent:%@\nextra:%@\n",
                                
                                [NSDateFormatter localizedStringFromDate:[NSDate date]
                                 
                                                               dateStyle:NSDateFormatterNoStyle
                                 
                                                               timeStyle:NSDateFormatterMediumStyle],
                                
                                title, content, [self logDic:extra]];
    
    NSLog(@"%@", currentContent);
    
    
    
    
    
    
    
    //    [_messageContents insertObject:currentContent atIndex:0];
    
    //
    
    //    NSString *allContent = [NSString
    
    //                            stringWithFormat:@"%@收到消息:\n%@\nextra:%@",
    
    //                            [NSDateFormatter
    
    //                             localizedStringFromDate:[NSDate date]
    
    //                             dateStyle:NSDateFormatterNoStyle
    
    //                             timeStyle:NSDateFormatterMediumStyle],
    
    //                            [_messageContents componentsJoinedByString:nil],
    
    //                            [self logDic:extra]];
    
    //
    
    //    _messageContentView.text = allContent;
    
    //    _messageCount++;
    
    //    [self reloadMessageCountLabel];
    
}
- (NSString *)logDic:(NSDictionary *)dic {
    
    if (![dic count]) {
        
        return nil;
        
    }
    
    NSString *tempStr1 =
    
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
     
                                                 withString:@"\\U"];
    
    NSString *tempStr2 =
    
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    
    NSString *tempStr3 =
    
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *str =
    
    [NSPropertyListSerialization propertyListFromData:tempData
     
                                     mutabilityOption:NSPropertyListImmutable
     
                                               format:NULL
     
                                     errorDescription:NULL];
    
    return str;
    
}


@end
